<?php
namespace app\common\exception;

use Exception;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;
use think\exception\PDOException;

class Handler extends Handle
{
    /**
     * 异常处理
     * @param Exception $e
     * @return Response
     */
    public function render(Exception $e)
    {
        if (config('app.app_debug')) {
            return parent::render($e);
        }

        // 参数验证错误
        if ($e instanceof ValidateException) {
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }

        // 请求异常
        if ($e instanceof HttpException) {
            return json(['code' => $e->getStatusCode(), 'msg' => $e->getMessage()]);
        }

        // 数据库异常
        if ($e instanceof PDOException) {
            return json(['code' => 500, 'msg' => '数据库错误']);
        }

        // 其他错误
        return json(['code' => 500, 'msg' => '系统错误']);
    }

    /**
     * 记录异常日志
     * @param Exception $e
     * @return void
     */
    protected function reportException(Exception $e)
    {
        // 记录日志
        $log = [
            'message' => $e->getMessage(),
            'file'    => $e->getFile(),
            'line'    => $e->getLine(),
            'trace'   => $e->getTraceAsString(),
            'time'    => date('Y-m-d H:i:s')
        ];
        
        trace($log, 'error');
    }
} 